<?php

namespace App\Http\Controllers\Home;

use App\Models\Findpwd;
use App\Models\Login;

class LoginController extends BaseController
{
    /**
     * 实例化
     */
    public function __construct(Login $login,Findpwd $findpwd)
    {
        parent::__construct();
        $this->login = $login;
        $this->findpwd = $findpwd;
    }

    /**
     * 用户中心
     */
    public function getIndex()
    {
        return view('home.login.index');
    }

    /**
     * 用户登录
     */
    public function postIndex()
    {
        $re = $this->login->login(request());
        $this->ajaxReturn($re);
    }

    public function postEmail()
    {
        $re = $this->login->email(request());
        $this->ajaxReturn($re);
    }

    /**
     * 退出
     */
    public function getLogout()
    {
        session()->flush();
        return redirect(urlHome('index', 'getIndex'));
    }

    /**
     * 忘记密码
     */
    public function getFindPwd()
    {
        return view('home.login.findPwd');
    }

    public function postFindPwd()
    {
        $res = $this->login->findPwd(request());
        if ($res['status'] == 1 || $res['status'] == 2) {
            return back()->with('message', $res['msg'])->withInput();
        }
    }

    /**
     * 密码找回
     */
    public function getResetPwd($key)
    {
        if (empty($key)) {
            return redirect(urlHome('index','getIndex'))->with('message','无效链接！')->withInput();
        }
        $findpwd_info = $this->findpwd->getOne(['token'=>$key]);
        if (!$findpwd_info) {
            return redirect(urlHome('index','getIndex'))->with('message','无效链接！')->withInput();
        }
        if (time() - $findpwd_info['add_time'] > 24 * 60 * 60) {
            $this->findpwd->del($findpwd_info['id']);
            return redirect(urlHome('index','getIndex'))->with('message','邮件已过期！')->withInput();
        }
        return view('home.login.resetpwd',compact('key'));
    }

    public function postResetPwd()
    {
        $re = $this->login->resetPwd(request());
        if ($re['status'] == 0) {
        return back()->with('message',$re['msg'])->withInput();
        }
        if ($re['status'] == 1) {
            return redirect(urlHome('login','getIndex'))->with('message',$re['msg'])->withInput();
        }
    }

    /**
     * 验证码加载
     */
    public function getCode()
    {
        $this->login->code(request());
    }
}
